package com.jpcc.vw.onlineRadio.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.RemoteException;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
/*Start by menglingqiang*/
import android.util.Log;
/*End by menglingqiang*/
import android.view.ActionMode;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cns.android.atmospherelamp.AtmosphereLampManager;
import com.google.gson.Gson;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.adapter.HotwordsAdapter;
import com.jpcc.vw.onlineRadio.adapter.SearchEntity;
import com.jpcc.vw.onlineRadio.adapter.SearchHistoryAdapter;
import com.jpcc.vw.onlineRadio.application.MusicApplication;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.db.DatabaseHelperOrm;
import com.jpcc.vw.onlineRadio.db.SearchHistoryDbBean;
import com.jpcc.vw.onlineRadio.http.HttpClient;
import com.jpcc.vw.onlineRadio.model.IRadio;
import com.jpcc.vw.onlineRadio.model.bean.BaseBean;
import com.jpcc.vw.onlineRadio.model.bean.HotwordsBean;
import com.jpcc.vw.onlineRadio.model.bean.HotwordsEntity;
import com.jpcc.vw.onlineRadio.model.bean.SearchHistoryBean;
import com.jpcc.vw.onlineRadio.model.bean.SearchHistoryResponseBean;
import com.jpcc.vw.onlineRadio.model.bean.SearchSyncBean;
import com.jpcc.vw.onlineRadio.model.bean.SuggestWordsBean;
import com.jpcc.vw.onlineRadio.model.bean.SuggestWordsEntity;
import com.jpcc.vw.onlineRadio.model.impl.RadioImpl;
import com.jpcc.vw.onlineRadio.utils.CommonSubscriber;
import com.jpcc.vw.onlineRadio.utils.EditTextUtil;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.jpcc.vw.tracelog.TracelogInterface;
import com.lzy.okhttpserver.download.DownloadManager;
import com.orhanobut.logger.Logger;
import com.zhy.http.okhttp.callback.StringCallback;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 搜索画面
 */
public class SearchActivity extends com.jpcc.vw.onlineRadio.base.BaseActivity {

    @BindView(R.id.layout_back)
    RelativeLayout layout_back;
    @BindView(R.id.tv_search)
    TextView tv_search;
    @BindView(R.id.edt_search_keyword)
    EditText edt_search_keyword;
    //    @BindView(R.id.imv_clear_search_history)
//    ImageView imv_clear_search_history;
//    @BindView(R.id.gridview_search_history)
//    GridView gridview_search_history;
//    @BindView(R.id.gridview_search_hotwords)
//    GridView gridview_search_hotwords;
    @BindView(R.id.list_search_history)
    ListView list_search_history;
    @BindView(R.id.layout_delete)
    RelativeLayout layout_delete;
    @BindView(R.id.layout_drop_down)
    RelativeLayout layout_drop_down;
    @BindView(R.id.imv_top_bottom_line)
    ImageView imv_top_bottom_line;
    @BindView(R.id.layout_drop)
    RelativeLayout layout_drop;
    @BindView(R.id.layout_cursor_control)
    LinearLayout layout_cursor_control;
    @BindView(R.id.layout_toleft)
    RelativeLayout layout_toleft;
    @BindView(R.id.layout_toright)
    RelativeLayout layout_toright;
    @BindView(R.id.imv_drop_down)
    ImageView imv_drop_down;
    @BindView(R.id.layout_delete_inner)
    RelativeLayout layout_delete_inner;
    @BindView(R.id.imv_toleft)
    ImageView imv_toleft;
    @BindView(R.id.imv_toright)
    ImageView imv_toright;

    private List<SearchEntity> datas = new ArrayList<>();
    private List<HotwordsEntity> hotwords = new ArrayList<>();
    private SearchHistoryAdapter adapter;
    private HotwordsAdapter hotwordsAdapter;
    private DatabaseHelperOrm helper;
    private IRadio radioModel;
    private List<String> realtedWords = new ArrayList<>();
    private Subscription subscription;
    private ArrayAdapter<String> adapterRelated;
    private BroadcastReceiver hanvonReceiver;
    private IntentFilter hanvonFilter;
    private BroadcastReceiver hideHanvonReceiver;


    @Override
    public int getLayoutId() {
        return R.layout.activity_search_new;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        helper = DatabaseHelperOrm.getHelper(this);
        radioModel = new RadioImpl();
        layout_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchActivity.this.finish();
            }
        });
//        for (int index=0;index<12;index++){
//            SearchHistoryEntity entity=new SearchHistoryEntity();
//            entity.setKeyword(index+"");
//            datas.add(entity);
//        }
        adapter = new SearchHistoryAdapter(this, datas);
        hotwordsAdapter = new HotwordsAdapter(this, hotwords);
//        gridview_search_history.setAdapter(adapter);
//        gridview_search_hotwords.setAdapter(hotwordsAdapter);
//        gridview_search_history.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
////                edt_search_keyword.setText(datas.get(position).getSearchWord());
//                Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
//                intent.putExtra("key_search_word", datas.get(position).getSearchWord());
////                refreshSearchHistory(datas.get(position).getSearchWord());
//                startActivity(intent);
//            }
//        });
        list_search_history.setAdapter(adapter);
        list_search_history.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (datas.get(position).getType() == 3) {
                    clearSearchHistory();
                } else {
                    Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
                    intent.putExtra("key_search_word", datas.get(position).getWords());
                    startActivity(intent);
                }
            }
        });
        edt_search_keyword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edt_search_keyword.setCursorVisible(true);
            }
        });
        list_search_history.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
//                edt_search_keyword.setFocusable(false);
//                Intent intent = new Intent("com.hanvon.inputmethod.IME_REQUEST_HIDE");
//                sendBroadcast(intent);
//                Logger.i("onScrollStateChanged scrollState-->"+scrollState);
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//                Intent intent = new Intent("com.hanvon.inputmethod.IME_REQUEST_HIDE");
//                sendBroadcast(intent);
//                edt_search_keyword.clearFocus();
//                edt_search_keyword.setFocusable(false);
            }
        });
//        gridview_search_hotwords.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
//                intent.putExtra("key_search_word", hotwords.get(position).getSearchWord());
////                refreshSearchHistory(hotwords.get(position).getSearchWord());
//                startActivity(intent);
//            }
//        });
//        prepareData();


        edt_search_keyword.setLongClickable(false);
        edt_search_keyword.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
            @Override
            public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
                return false;
            }

            @Override
            public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
                return false;
            }

            @Override
            public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
                return false;
            }

            @Override
            public void onDestroyActionMode(ActionMode actionMode) {

            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            edt_search_keyword.setCustomInsertionActionModeCallback(new ActionMode.Callback() {
                @Override
                public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
                    return false;
                }

                @Override
                public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
                    return false;
                }

                @Override
                public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
                    return false;
                }

                @Override
                public void onDestroyActionMode(ActionMode actionMode) {

                }
            });
        }

        layout_delete_inner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(edt_search_keyword.getText().toString())) {
                    Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
                    intent.putExtra("key_search_word", edt_search_keyword.getText().toString());
                    startActivity(intent);

                } else {
                    ToastUtils.show(R.string.string_110);
                }
            }
        });
        edt_search_keyword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(edt_search_keyword.getText().toString())) {
//                        refreshSearchHistory(edt_search_keyword.getText().toString());


                        Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
                        intent.putExtra("key_search_word", edt_search_keyword.getText().toString());
                        startActivity(intent);

                    } else {
                        ToastUtils.show(R.string.string_110);
                    }
                }
                return false;
            }
        });
        layout_drop_down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(edt_search_keyword.getText().toString())) {
                    ToastUtils.show(R.string.string_110);
                } else {
                    Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
                    intent.putExtra("key_search_word", edt_search_keyword.getText().toString());
                    startActivity(intent);
                }
            }
        });


        list_search_history.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(edt_search_keyword.getWindowToken(), 0);
                edt_search_keyword.setCursorVisible(false);
                return false;
            }
        });


        adapterRelated = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, realtedWords);
        layout_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(edt_search_keyword.getText().toString())) {
//                    if (edt_search_keyword.getText().toString().length() == 1) {
//                        edt_search_keyword.setText("");
//                    } else {
//                        edt_search_keyword.setText(edt_search_keyword.getText().toString().substring(0, edt_search_keyword.getText().toString().length() - 1));
//                        edt_search_keyword.setSelection(edt_search_keyword.getText().length());
//                    }
                    edt_search_keyword.setText("");
                }
            }
        });
//        edt_search_keyword.setAdapter(adapterRelated);
//        edt_search_keyword.setDropDownAnchor(R.id.edt_search_keyword);
//        edt_search_keyword.setDropDownHeight(200);
//        edt_search_keyword.setThreshold(1);
//        edt_search_keyword.setDropDownVerticalOffset(100);
        edt_search_keyword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                edt_search_keyword.setEllipsize(TextUtils.TruncateAt.END);
                String q = s.toString();
                if (TextUtils.isEmpty(q)) {
                    prepareData();
                } else {
                    getSuggestWords();
                }

                if (TextUtils.isEmpty(edt_search_keyword.getText().toString())) {
                    imv_toleft.setBackgroundResource(R.drawable.cursor_left_press);
                    imv_toright.setBackgroundResource(R.drawable.cursor_right_press);
                } else {
                    int selection = edt_search_keyword.getSelectionStart();
                    if (selection > 0) {
                        if (selection < edt_search_keyword.getText().length()) {
                            imv_toleft.setBackgroundResource(R.drawable.bg_status_pointer_to_left);
                            imv_toright.setBackgroundResource(R.drawable.bg_status_pointer_to_right);
                        } else {
                            imv_toleft.setBackgroundResource(R.drawable.bg_status_pointer_to_left);
                            imv_toright.setBackgroundResource(R.drawable.cursor_right_press);
                        }
                    } else {
                        imv_toleft.setBackgroundResource(R.drawable.cursor_left_press);
                        imv_toright.setBackgroundResource(R.drawable.bg_status_pointer_to_right);
                    }
                }

            }
        });

        tv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(edt_search_keyword.getText().toString())) {
//                    refreshSearchHistory(edt_search_keyword.getText().toString());
                    Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
                    intent.putExtra("key_search_word", edt_search_keyword.getText().toString());
                    startActivity(intent);
                } else {
                    ToastUtils.show(R.string.string_110);
                }
            }
        });
        layout_drop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (layout_cursor_control.getVisibility() == View.VISIBLE) {
                    layout_cursor_control.setVisibility(View.INVISIBLE);
                    imv_drop_down.setBackgroundResource(R.drawable.bg_status_drop_down_normal);
                } else {
                    layout_cursor_control.setVisibility(View.VISIBLE);
//                    imv_drop_down.setBackgroundResource(R.drawable.bg_status_drop_down_up);
                    imv_drop_down.setBackgroundResource(R.drawable.bg_status_drop_down_normal);
                }

                if (TextUtils.isEmpty(edt_search_keyword.getText().toString())) {
                    imv_toleft.setBackgroundResource(R.drawable.cursor_left_press);
                    imv_toright.setBackgroundResource(R.drawable.cursor_right_press);
                } else {
                    int selection = edt_search_keyword.getSelectionStart();
                    if (selection > 0) {
                        if (selection < edt_search_keyword.getText().length()) {
                            imv_toleft.setBackgroundResource(R.drawable.bg_status_pointer_to_left);
                            imv_toright.setBackgroundResource(R.drawable.bg_status_pointer_to_right);
                        } else {
                            imv_toleft.setBackgroundResource(R.drawable.bg_status_pointer_to_left);
                            imv_toright.setBackgroundResource(R.drawable.cursor_right_press);
                        }
                    } else {
                        imv_toleft.setBackgroundResource(R.drawable.cursor_left_press);
                        imv_toright.setBackgroundResource(R.drawable.bg_status_pointer_to_right);
                    }
                }
            }
        });
        layout_toleft.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        layout_toleft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!edt_search_keyword.hasFocus()) {
                    edt_search_keyword.requestFocus();
                }
                if (TextUtils.isEmpty(edt_search_keyword.getText().toString())) {
                    return;
                }
                int selection = edt_search_keyword.getSelectionStart();
                if (selection > 0) {
                    edt_search_keyword.setSelection(selection - 1);
                }

                selection = edt_search_keyword.getSelectionStart();
                if (selection > 0) {
                    imv_toleft.setBackgroundResource(R.drawable.bg_status_pointer_to_left);
                    imv_toright.setBackgroundResource(R.drawable.bg_status_pointer_to_right);
                } else {
                    imv_toleft.setBackgroundResource(R.drawable.cursor_left_press);
                    imv_toright.setBackgroundResource(R.drawable.bg_status_pointer_to_right);
                }
            }
        });
        layout_toright.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!edt_search_keyword.hasFocus()) {
                    edt_search_keyword.requestFocus();
                }
                int selection = edt_search_keyword.getSelectionStart();
                if (selection < edt_search_keyword.getText().length()) {
                    edt_search_keyword.setSelection(selection + 1);
                }

                selection = edt_search_keyword.getSelectionStart();
                if (selection < edt_search_keyword.getText().length()) {
                    imv_toleft.setBackgroundResource(R.drawable.bg_status_pointer_to_left);
                    imv_toright.setBackgroundResource(R.drawable.bg_status_pointer_to_right);
                } else {
                    imv_toleft.setBackgroundResource(R.drawable.bg_status_pointer_to_left);
                    imv_toright.setBackgroundResource(R.drawable.cursor_right_press);
                }
            }
        });
        initHanvonReceiver();
        hideHanvonReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null) {
                    if ("com.hanvon.inputmethod.IME_HIDE".equals(intent.getAction())) {
                        edt_search_keyword.setCursorVisible(false);
                    }
                }
            }
        };
        IntentFilter hideHanvonFilter = new IntentFilter("com.hanvon.inputmethod.IME_HIDE");
        this.registerReceiver(hideHanvonReceiver, hideHanvonFilter);
//        getSearchHistory();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
//        edt_search_keyword.setDropDownHeight(300);
        super.onWindowFocusChanged(hasFocus);
    }


    private void clearSearchHistory() {
        if (radioModel == null) {
            radioModel = new RadioImpl();
        }
        radioModel.ClearSearchHistory().subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                DeleteBuilder deleteBuilder = null;
                try {
                    deleteBuilder = DatabaseHelperOrm.getHelper(SearchActivity.this).getSearchHistoryDao().deleteBuilder();
                    deleteBuilder.where().eq("userId", MusicApplication.GetUserId());
                    deleteBuilder.delete();
                    ToastUtils.show(R.string.string_64);
                    prepareData();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(BaseBean response) {
                ToastUtils.show(response.getStatusMessage());
            }
        });
    }

    @Override
    public void doAtmosphere(boolean rgbOn, String color) {
        Logger.i("doAtmosphere" + "rgbOn-->" + rgbOn);
        Logger.i("doAtmosphere" + "color-->" + color);
        if (rgbOn) {
            if (TextUtils.isEmpty(color)) {
                imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
            } else {
                imv_top_bottom_line.setColorFilter(Color.parseColor(color));
            }
        } else {
            imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        prepareData();
//        getSearchHistory();
        this.registerReceiver(hanvonReceiver, hanvonFilter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        this.unregisterReceiver(hanvonReceiver);
    }

    private void syncSearchHistory() {
        try {
            SearchSyncBean syncBean = new SearchSyncBean();
            syncBean.setKeywords("");
            List<SearchHistoryDbBean> sources = helper.getSearchHistoryDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).query();
            if (sources != null && sources.size() > 0) {
                for (SearchHistoryDbBean db : sources) {
                    syncBean.setKeywords(syncBean.getKeywords() + db.getSearchWord() + ",");
                }
                syncBean.setKeywords(syncBean.getKeywords().substring(0, syncBean.getKeywords().length() - 1));
                String jsonSync = new Gson().toJson(syncBean);
                Logger.i("jsonSync-->" + jsonSync);
                HttpClient.SyncSearchHistory(jsonSync, new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Logger.i(e.toString());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Logger.i(response.toString());
                        BaseBean result = new Gson().fromJson(response, BaseBean.class);
                    }
                });
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    private void initHanvonReceiver() {
        hanvonFilter = new IntentFilter("com.hanvon.inputmethod.IME_START");
        hanvonReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                sendHotWrodsToHanvon();
            }
        };
    }


    private void sendHotWrodsToHanvon() {
        if (radioModel == null) {
            radioModel = new RadioImpl();
        }
        radioModel.GetHotWords().subscribe(new CommonSubscriber<HotwordsBean>() {
            @Override
            public void onSuccess(HotwordsBean response) {
                ArrayList<String> values = new ArrayList<>();
                int size = 0;
                if (response.getData() != null) {
                    size = response.getData().size();
                }
                String[] hotwordsLocal = new String[size];
                for (int index = 0; index < response.getData().size(); index++) {
                    hotwordsLocal[index] = response.getData().get(index).getSearchWord();
                }
                Intent intent = new Intent();
                intent.setAction("com.hanvon.inputmethod.HOT_WORDS");
                intent.putExtra("hot_words", hotwordsLocal);
                sendBroadcast(intent);
            }

            @Override
            public void onFailure(BaseBean response) {

            }
        });
    }


    @Override
    protected void onDestroy() {
        if (hideHanvonReceiver != null) {
            this.unregisterReceiver(hideHanvonReceiver);
        }
        super.onDestroy();
//        if(hanvonReceiver!=null){
//            this.unregisterReceiver(hanvonReceiver);
//        }
    }

    private void getSearchHistory() {

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), SearchActivity.this.getClass().getName(), "DEBUG", null, "GetSearchHistory request");
            } else {
                Log.e("jgj", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        radioModel.GetSearchHistory().subscribe(new CommonSubscriber<SearchHistoryResponseBean>() {
            @Override
            public void onSuccess(SearchHistoryResponseBean response) {
                Logger.i(response.toString());
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), SearchActivity.this.getClass().getName(), "DEBUG", response.getStatusCode().toString(), "GetSearchHistory onSuccess");
                    } else {
                        Log.e("jgj", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/


                DeleteBuilder deleteBuilder = null;
                try {
                    deleteBuilder = helper.getSearchHistoryDao().deleteBuilder();
                    deleteBuilder.where().eq("userId", MusicApplication.GetUserId());
                    deleteBuilder.delete();


                    for (SearchHistoryBean bean : response.getData()) {
                        SearchHistoryDbBean onlineBean=new SearchHistoryDbBean();
                        onlineBean.setUserId(MusicApplication.GetInstance().GetUserId());
                        onlineBean.setSearchWord(bean.getKeyword());
                        onlineBean.setTimeStamp(bean.getSearchTimestamp());
                        helper.getSearchHistoryDao().create(onlineBean);
                    }
prepareData();

                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(BaseBean response) {
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), SearchActivity.this.getClass().getName(), "ERROR", response.getStatusCode().toString(), "GetSearchHistory onSuccess");
                    } else {
                        Log.e("jgj", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }
        });
    }

    private void refreshSearchHistory(String searchWord) {
        try {
            SearchHistoryDbBean result = helper.getSearchHistoryDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("searchWord", searchWord).queryForFirst();
            if (result == null) {
                result = new SearchHistoryDbBean();
                result.setUserId(MusicApplication.GetUserId());
                result.setSearchWord(searchWord);
                result.setTimeStamp(new Date().getTime());
                helper.getSearchHistoryDao().create(result);
            } else {
                result.setTimeStamp(new Date().getTime());
                helper.getSearchHistoryDao().update(result);
            }
            prepareData();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setupData() {
        getSearchHotwords();
        if (Constants.isRelease) {
            try {
                boolean atmosphereStatus = AtmosphereLampManager.getInstance(this).isHmiAtmosphereLampOn();
                String color = AtmosphereLampManager.getInstance(this).getHmiAtmosphereLampColor();
                doAtmosphere(atmosphereStatus, color);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }


    private void getSuggestWords() {
        if (subscription != null) {
            subscription.unsubscribe();
        }

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), SearchActivity.this.getClass().getName(), "DEBUG", null, "GetSearchSuggestWords request");
            } else {
                Log.e("jgj", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        subscription = radioModel.GetSearchSuggestWords(edt_search_keyword.getText().toString()).subscribe(new CommonSubscriber<SuggestWordsBean>() {
            @Override
            public void onSuccess(SuggestWordsBean response) {

                if (response.getData() != null && response.getData().getKeywords() != null && response.getData().getKeywords().size() > 0) {
//                    Logger.i("getSuggestWords()-->onSuccess");
//                    List<String> autoString = new ArrayList<>();
//                    for (SuggestWordsEntity entity : response.getData().getKeywords()) {
//                        autoString.add(entity.getKeyword());
//                    }
//
//
//                    realtedWords.clear();
//                    realtedWords.addAll(autoString);
////                    edt_search_keyword.setAdapter(adapterRelated);
////                    adapterRelated.notifyDataSetChanged();
//
//
//                    adapterRelated = new ArrayAdapter<String>(SearchActivity.this,
//                            android.R.layout.simple_list_item_1, realtedWords);
//                    edt_search_keyword.setAdapter(adapterRelated);
//                    adapterRelated.notifyDataSetChanged();


//                    adapterRelated.notifyDataSetChanged();
//                    doAutoComplete();


                    datas.clear();
                    for (SuggestWordsEntity entity : response.getData().getKeywords()) {
                        SearchEntity search = new SearchEntity();
                        search.setType(2);
                        search.setWords(entity.getKeyword());
                        datas.add(search);
                    }
                    adapter.setDatas(datas);
                } else {
                    Logger.i("getSuggestWords()-->onSuccessEmpty");
//                    List<String> autoString = new ArrayList<>();
//                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(SearchActivity.this,
//                            android.R.layout.simple_dropdown_item_1line, autoString);
//                    edt_search_keyword.setAdapter(adapter);
//                    realtedWords.clear();
//                    adapterRelated.notifyDataSetChanged();


                }
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), SearchActivity.this.getClass().getName(), "DEBUG", response.getStatusCode().toString(), "GetSearchSuggestWords onSuccess");
                    } else {
                        Log.e("jgj", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }

            @Override
            public void onFailure(BaseBean response) {
//                List<String> autoString = new ArrayList<>();
//                ArrayAdapter<String> adapter = new ArrayAdapter<String>(SearchActivity.this,
//                        android.R.layout.simple_dropdown_item_1line, autoString);
//                edt_search_keyword.setAdapter(adapter);
                Logger.i("getSuggestWords()-->onFailure");
//                ToastUtils.show(response.getStatusMessage());
                realtedWords.clear();
                adapterRelated.notifyDataSetChanged();
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), SearchActivity.this.getClass().getName(), "ERROR", response.getStatusCode().toString(), "GetSearchSuggestWords onFailure");
                    } else {
                        Log.e("jgj", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }
        });
    }

    private void doAutoComplete() {

        Observable.just("Amit")
                //延时两秒，第一个参数是数值，第二个参数是事件单位
                .delay(2, TimeUnit.SECONDS)
                // Run on a background thread
                .observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(String s) {
//                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(SearchActivity.this,
//                                android.R.layout.simple_list_item_1, realtedWords);
//                        adapter.addAll();
//                        edt_search_keyword.setAdapter(adapter);
//                        edt_search_keyword.setDropDownHeight(850);
//                        edt_search_keyword.setThreshold(1);
//                        edt_search_keyword.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                            @Override
//                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                                Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
//                                intent.putExtra("key_search_word", realtedWords.get(position));
//                                refreshSearchHistory(realtedWords.get(position));
//                                startActivity(intent);
//                            }
//                        });
                        adapterRelated.clear();
                        adapterRelated.addAll(realtedWords);
                        adapterRelated.notifyDataSetChanged();
                    }
                });//这里的观察者依然不重要


    }


    private void getSearchHotwords() {

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), SearchActivity.this.getClass().getName(), "DEBUG", null, "GetHotWords request");
            } else {
                Log.e("jgj", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        radioModel.GetHotWords().subscribe(new CommonSubscriber<HotwordsBean>() {
            @Override
            public void onSuccess(HotwordsBean response) {
                if (response.getData() != null && response.getData().size() > 0) {
                    hotwords.clear();
                    for (HotwordsEntity entity : response.getData()) {
                        if (hotwords.size() < 6) {
                            hotwords.add(entity);
                        }
                    }
//                    hotwords.addAll(response.getData());
                    hotwordsAdapter.setDatas(hotwords);
                } else {

                }
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), SearchActivity.this.getClass().getName(), "DEBUG", response.getStatusCode().toString(), "GetHotWords onSuccess");
                    } else {
                        Log.e("jgj", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }

            @Override
            public void onFailure(BaseBean response) {
                ToastUtils.show(response.getStatusMessage());
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), SearchActivity.this.getClass().getName(), "DEBUG", response.getStatusCode().toString(), "GetHotWords onFailure");
                    } else {
                        Log.e("jgj", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }
        });
    }


    private void prepareData() {
//        try {
//            List<SearchHistoryDbBean> sources = helper.getSearchHistoryDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).query();
//            if (sources.size() > 0) {
//                if (sources.size() > 10) {
//                    datas.clear();
//                    for (int index = 0; index < 10; index++) {
//                        datas.add(sources.get(index));
//                    }
//                } else {
//                    datas.clear();
//                    datas.addAll(sources);
//                }
////                imv_clear_search_history.setVisibility(View.VISIBLE);
//            } else {
//                datas.clear();
//                datas.addAll(sources);
////                imv_clear_search_history.setVisibility(View.INVISIBLE);
//            }
//            adapter.setDatas(datas);
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), SearchActivity.this.getClass().getName(), "DEBUG", null, "prepareData GetHotWords request");
            } else {
                Log.e("jgj", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        radioModel.GetHotWords().subscribe(new CommonSubscriber<HotwordsBean>() {
            @Override
            public void onSuccess(HotwordsBean response) {
                datas.clear();
                for (HotwordsEntity data : response.getData()) {
                    SearchEntity entity = new SearchEntity();
                    entity.setType(0);
                    entity.setWords(data.getSearchWord());
                    if (datas.size() == 0) {
                        entity.setVisible(true);
                    }
//                    datas.add(entity);
                }
//                String keywords = PreferenceUtils.GetSearchKeywords();
//                if (!TextUtils.isEmpty(keywords)) {
//                    List<String> keywordList = new ArrayList<>();
//                    keywordList.addAll(Arrays.asList(keywords.split(",")));
//                    for (int index=0;index<keywordList.size();index++){
//                        SearchEntity entity = new SearchEntity();
//                        entity.setType(1);
//                        entity.setWords(keywordList.get(index));
//                        if(index==0){
//                            entity.setVisible(true);
//                        }
//                        datas.add(entity);
//                    }
//                }
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), SearchActivity.this.getClass().getName(), "DEBUG", response.getStatusCode().toString(), "GetHotWords onSuccess");
                    } else {
                        Log.e("jgj", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/

                try {
                    List<SearchHistoryDbBean> sources = helper.getSearchHistoryDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).query();
                    if (sources != null && sources.size() > 0) {
                        for (int index = 0; index < sources.size() && index < 10; index++) {
                            SearchEntity entity = new SearchEntity();
                            entity.setType(1);
                            entity.setWords(sources.get(index).getSearchWord());
                            if (index == 0) {
                                entity.setVisible(true);
                            }
                            datas.add(entity);
                        }
                        SearchEntity entity = new SearchEntity();
                        entity.setType(3);
                        entity.setWords(getResources().getString(R.string.string_52));
                        datas.add(entity);
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }


                adapter.setDatas(datas);
            }

            @Override
            public void onFailure(BaseBean response) {
//                String keywords = PreferenceUtils.GetSearchKeywords();
//                if (!TextUtils.isEmpty(keywords)) {
//                    List<String> keywordList = new ArrayList<>();
//                    List<SearchEntity> keywordEntityList = new ArrayList<>();
//                    keywordList.addAll(Arrays.asList(keywords.split(",")));
//                    for (int index=0;index<keywordList.size();index++){
//                        SearchEntity entity = new SearchEntity();
//                        entity.setType(1);
//                        entity.setWords(keywordList.get(index));
//                        if(index==0){
//                            entity.setVisible(true);
//                        }
//                        keywordEntityList.add(entity);
//                    }
//                    datas.clear();
//                    datas.addAll(keywordEntityList);
//                    adapter.setDatas(keywordEntityList);
//                }
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), SearchActivity.this.getClass().getName(), "ERROR", response.getStatusCode().toString(), "GetHotWords onFailure");
                    } else {
                        Log.e("jgj", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/


                try {
                    List<SearchHistoryDbBean> sources = helper.getSearchHistoryDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).query();
                    if (sources != null && sources.size() > 0) {
                        for (int index = 0; index < sources.size(); index++) {
                            SearchEntity entity = new SearchEntity();
                            entity.setType(1);
                            entity.setWords(sources.get(index).getSearchWord());
                            if (index == 0) {
                                entity.setVisible(true);
                            }
                            datas.add(entity);
                        }
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }


            }
        });

    }
}
